import {sql} from "../config/db.js";

export async function getTransactionByUserId(req, res) {
    try {
        const {userId} = req.params;
        const transactions = await sql`
            select *
            from transactions
            where user_id = ${userId}
            order by created_at desc
        `
        res.status(200).json({transactions: transactions})
    } catch (error) {
        console.log("Error getting the transactions", error)
        res.status(500).json({message: "Internal Server Error"})
    }
}

export async function createTransaction(req, res) {
    try {
        const {userId} = req.params;
        const transactions = await sql`
            select *
            from transactions
            where user_id = ${userId}
            order by created_at desc
        `
        res.status(200).json({transactions: transactions})
    } catch (error) {
        console.log("Error getting the transactions", error)
        res.status(500).json({message: "Internal Server Error"})
    }
}

export async function deleteTransactionById(req, res) {
    try {
        const {id} = req.params;
        if (isNaN(parseInt(id))) {
            return res.status(400).json({message: "Incorrect id"})
        }
        await sql`delete
                  from transactions
                  where id = ${id}`
        return res.status(200).json({message: "Transaction deleted successfully"})
    } catch (error) {
        return res.status(500).json({message: "Internal Server Error"})
    }
}

export async function getSummaryByUserId(req, res) {
    try {
        const {userId} = req.params;
        const balanceResult = await sql`
            select coalesce(sum(amount), 0) as balance
            from transactions
            where user_id = ${userId}
        `;
        const incomeResult = await sql`
            select coalesce(sum(amount), 0) as income
            from transactions
            where user_id = ${userId}
              and amount > 0`;
        const expensesResult = await sql`
            select coalesce(sum(amount), 0) as expenses
            from transactions
            where user_id = ${userId}
              and amount < 0`;
        console.log("get res", balanceResult, incomeResult, expensesResult)
        return res.status(200).json({
                balance: balanceResult,
                income: incomeResult,
                expenses: expensesResult
            }
        )
    } catch (error) {
        res.status(500).json({message: "Internal Server Error"})
    }
}
